"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RichTextMiniAdapter = void 0;

var _check = _interopRequireDefault(require("../../check"));

var _icon = _interopRequireDefault(require("../../icon"));

var _taro = _interopRequireDefault(require("@tarojs/taro"));

var _components = require("@tarojs/components");

var _reactHtmlParser = require("@hedgedoc/html-to-react");

var _get = require("../../../utils/get");

var _react = _interopRequireDefault(require("react"));

var _core = _interopRequireDefault(require("highlight.js/lib/core"));

var _util = require("./util");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var qs = require('qs');

var initHighLight = function initHighLight() {
  _core.default.registerLanguage('c', require('highlight.js/lib/languages/c'));

  _core.default.registerLanguage('cpp', require('highlight.js/lib/languages/c'));

  _core.default.registerLanguage('xml', require('highlight.js/lib/languages/xml'));

  _core.default.registerLanguage('java', require('highlight.js/lib/languages/java'));

  _core.default.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));

  _core.default.registerLanguage('css', require('highlight.js/lib/languages/css'));

  _core.default.registerLanguage('nginx', require('highlight.js/lib/languages/nginx'));

  _core.default.registerLanguage('sql', require('highlight.js/lib/languages/sql'));

  _core.default.registerLanguage('typescript', require('highlight.js/lib/languages/typescript'));

  _core.default.registerLanguage('markdown', require('highlight.js/lib/languages/markdown'));

  _core.default.registerLanguage('go', require('highlight.js/lib/languages/go'));

  _core.default.registerLanguage('php', require('highlight.js/lib/languages/php'));

  _core.default.registerLanguage('python', require('highlight.js/lib/languages/python'));

  _core.default.registerLanguage('shell', require('highlight.js/lib/languages/shell'));
};

initHighLight();
var RichTextMiniAdapter = {
  getNodeText: function getNodeText(node) {
    var _this = this;

    var nodeText = '';

    if (node.children && node.children.length > 0) {
      node.children.forEach(function (element) {
        nodeText += _this.adapter.getNodeText(element);
      });
    }

    if (node.name === 'br') {
      nodeText += '\n';
    }

    if (node.type === 'text') {
      nodeText += "".concat(node.data);
    }

    return nodeText;
  },

  /**
   * 解析 Code 模块
   * @param node 目标节点
   */
  parseCodeContent: function parseCodeContent(node) {
    var codeString = this.adapter.getNodeText(node); // hljs处理后，把回车换行符标记替换为带类名的view标签，用于小程序代码块保持换行

    var highlightedHTML = _core.default.highlightAuto(codeString).value;

    highlightedHTML = highlightedHTML.replace(/\r|\n/g, '<view class="dzq-code__divider"></view>');

    var highlightedNodes = _reactHtmlParser.htmlparser2.parseDOM(highlightedHTML, {
      decodeEntities: true
    });

    node.children = highlightedNodes;
    node.name = _components.View;
    return node;
  },

  /**
   * 适配于 Taro 的转换函数，使用特定的 class，用 View 模拟
   * @param {*} node
   * @param {*} index
   */
  transform: function transform(node, index) {
    if (node.type === 'tag') {
      this.idCount += 1;

      if (node.attribs) {
        node.attribs = _objectSpread(_objectSpread({}, node.attribs), {}, {
          class: "dzq-".concat(node.name, " ").concat((0, _get.get)(node.attribs, 'class', '')),
          'data-nodeId': this.idCount,
          dataNodeId: this.idCount,
          dataset: {
            nodeId: this.idCount
          },
          originType: node.name,
          transformedStyle: (0, _util.InlineStyleToObject)((0, _get.get)(node.attribs, 'style', ''))
        });
        this.nodes[this.idCount] = node;
      }

      switch (node.name) {
        case 'img':
          node.name = _components.Image;
          this.imgUrls.push(node.attribs.src);
          return /*#__PURE__*/_react.default.createElement(_components.Image, _extends({}, node.attribs, {
            dataset: {
              nodeId: node.attribs.dataNodeId
            },
            style: node.attribs.transformedStyle,
            mode: 'widthFix'
          }));

        case 'code':
          {
            node = this.adapter.parseCodeContent(node);
            node.name = _components.View;
            break;
          }

        case 'span':
          {
            node.name = _components.Text;
            break;
          }

        case 'input':
          {
            var checkLabelState = (0, _get.get)(node, 'parent.attribs.data-task-state', {});
            return /*#__PURE__*/_react.default.createElement(_check.default, {
              checked: checkLabelState === 'checked'
            });
          }

        case 'iframe':
          {
            node.attribs.originType = 'a';
            this.nodes[this.idCount] = node; // 白名单内的节点才渲染

            if (this.isValidIframeSrc(node.attribs.src)) {
              // return <View {...node.attribs} className="dzq-a">复制音视频链接</View>
              return this.adapter.iframeRender(node);
            }

            return null;
          }

        default:
          node.name = _components.View;
      }

      node.attribs = _objectSpread({}, node.attribs);
      node.attribs.transformedStyle = (0, _get.get)(node.attribs, "style", "");
      return (0, _reactHtmlParser.convertNodeToElement)(node, index, this.adapter.transform);
    }
  },

  /**
   * 小程序 iframe 渲染函数，渲染可跳转小程序的 iframe
   * @param node
   */
  iframeRender: function iframeRender(node) {
    var _node$attribs$src$spl = node.attribs.src.split('?'),
        _node$attribs$src$spl2 = _slicedToArray(_node$attribs$src$spl, 2),
        hostname = _node$attribs$src$spl2[0],
        _node$attribs$src$spl3 = _node$attribs$src$spl2[1],
        query = _node$attribs$src$spl3 === void 0 ? '' : _node$attribs$src$spl3;

    var jumpStrategy = function jumpStrategy() {};

    var parsedQuery = qs.parse(query);
    jumpStrategy = this.adapter.iframeJumpStrategy({
      hostname: hostname,
      query: parsedQuery,
      node: node
    });
    var urlRegexp = /^(http[s]?[\:]?)?\/\/([a-zA-Z0-9\.]+)\/[\s\S]*/;

    var _ref = urlRegexp.exec(hostname) || [],
        _ref2 = _slicedToArray(_ref, 3),
        realHostname = _ref2[2];

    return /*#__PURE__*/_react.default.createElement(_components.View, _extends({}, node.attribs, {
      onClick: jumpStrategy,
      className: "dzq-a dzq-mini-iframe"
    }), /*#__PURE__*/_react.default.createElement(_components.View, {
      className: 'dzq-mini-iframe-icon'
    }, /*#__PURE__*/_react.default.createElement(_icon.default, {
      name: 'VideoOutlined',
      size: 28
    })), /*#__PURE__*/_react.default.createElement(_components.View, {
      className: 'dzq-mini-iframe-info'
    }, /*#__PURE__*/_react.default.createElement(_components.View, {
      className: 'dzq-mini-iframe-host'
    }, "\u6765\u81EA ", realHostname, " \u7684\u97F3\u89C6\u9891"), /*#__PURE__*/_react.default.createElement(_components.View, {
      className: 'dzq-mini-iframe-action'
    }, "\u67E5\u770B")));
  },
  iframeJumpStrategy: function iframeJumpStrategy(_ref3) {
    var _this2 = this;

    var _ref3$hostname = _ref3.hostname,
        hostname = _ref3$hostname === void 0 ? '' : _ref3$hostname,
        _ref3$query = _ref3.query,
        query = _ref3$query === void 0 ? {} : _ref3$query,
        _ref3$node = _ref3.node,
        node = _ref3$node === void 0 ? {} : _ref3$node;

    var callbackFactory = function callbackFactory(cb) {
      return function (e) {
        _this2.onLinkClick(node, e);

        _this2.onClick(e, node);

        e.stopPropagation();
        cb();
      };
    };

    if (hostname.indexOf('bilibili') !== -1) {
      var _ref4 = query,
          aid = _ref4.aid;

      if (aid) {
        return callbackFactory(function () {
          return _taro.default.navigateToMiniProgram({
            appId: 'wx7564fd5313d24844',
            path: "pages/video/video?avid=".concat(aid)
          });
        });
      }
    }

    if (hostname.indexOf('163') !== -1) {
      var _ref5 = query,
          id = _ref5.id;

      if (id) {
        return callbackFactory(function () {
          return _taro.default.navigateToMiniProgram({
            appId: 'wx32431e4d2e38cc7b',
            path: "pages/song/song?id=".concat(id, "&source=list")
          });
        });
      }
    }

    if (hostname.indexOf('qq') !== -1) {
      var _ref6 = query,
          vid = _ref6.vid;

      if (vid) {
        return callbackFactory(function () {
          return _taro.default.navigateToMiniProgram({
            appId: 'wxa75efa648b60994b',
            path: "preload_play/play/index?vid=".concat(vid)
          });
        });
      }
    }

    if (hostname.indexOf('youku') !== -1) {
      var splitArray = hostname.split('/');

      if (splitArray.length > 1) {
        var _id = splitArray[splitArray.length - 1];

        if (_id) {
          return callbackFactory(function () {
            return _taro.default.navigateToMiniProgram({
              appId: 'wx5de0c309a1472da6',
              path: "pages/play/play?srcType=1&showId=".concat(_id)
            });
          });
        }
      }
    } // FIXME: 爱奇艺需要获取 qipuid 才能跳转成功
    // if (hostname.indexOf('iqiyi') !== -1) {
    //   const { tvid } = query as any;
    //
    //   return () => Taro.navigateToMiniProgram({
    //     appId: 'wxcd10170e55a1f55d',
    //     path: `pages/video/video?aid=${tvid}&rfr=wx_home&useRecord=false&qipuId=${tvid}`
    //   })
    // }


    var noop = function noop() {};

    return callbackFactory(noop);
  },
  onWrapperClick: function onWrapperClick(e) {
    var nodeId = (0, _get.get)(e, 'target.dataset.nodeId', '') || (0, _get.get)(e, 'target.dataset.nodeid', '');

    if (!nodeId) {
      this.onClick(e, {});
      return;
    }

    var targetNode = this.nodes[nodeId];

    if (targetNode) {
      var originType = (0, _get.get)(targetNode, 'attribs.originType', '');

      if (originType === 'img') {
        // emoji 表情外才能触发点击事件
        if ((0, _get.get)(targetNode, 'attribs.class', '').indexOf('qq-emotion') === -1) {
          this.onImgClick(targetNode, e);
        }
      }

      if (originType === 'a') {
        console.log('no link click', targetNode, e);
        this.onLinkClick(targetNode, e);
        e && e.stopPropagation();
      }

      this.onClick(e, targetNode);
    }
  }
};
exports.RichTextMiniAdapter = RichTextMiniAdapter;
